$(function () {
    // 实例化fastclick
    FastClick.attach(document.body);
    var hostUrl = 'https://api.wdb007.com/wdb-wxapp-test/';
    // var hostUrl = 'https://api.wdb007.com/wdb-wxapp/';

    // 从url中获取userId,usertoken.....
    var Request = new Object();
    Request = GetRequest();
    var userid = Request['userid'];
    var parentHdUid = Request['parentHdUid'];
    var usertoken = Request['usertoken'];
    // 获取好友领取奖品信息
    var rankList = [];


    var rankListCount = 0;

    if (sessionStorage.getItem('usertoken') == null || sessionStorage.getItem('usertoken') == undefined || sessionStorage.getItem('usertoken') == 'undefined') {
        sessionStorage.setItem('usertoken', usertoken);

    }

    if (sessionStorage.getItem('userid') == undefined && userid != undefined) {
        sessionStorage.setItem('userid', userid);
        console.log('sesstionStroge----userid', sessionStorage.getItem('userid') == undefined);
    }

    console.log('sessionStorage', sessionStorage.getItem('usertoken'), sessionStorage.getItem('userid'))
    if (parentHdUid && parentHdUid != 'undefined') {
        $('#goto_index').show();
    } else {
        $('#goto_index').hide()
    }

    // $('#userid_').html(userid);
    // $('#parentHdUid_').html(parentHdUid);
    // $('#usertoken_').html(sessionStorage.getItem('usertoken'));


    var lottery = {
        index: 1, //当前转动到哪个位置，起点位置
        count: 0, //总共有多少个位置
        timer: 0, //setTimeout的ID，用clearTimeout清除
        speed: 20, //初始转动速度
        times: 0, //转动次数
        cycle: 50, //转动基本次数：即至少需要转动多少次再进入抽奖环节
        prize: 1, //中奖位置
        isLight: false,
        init: function (id) {
            if ($("#" + id).find(".lottery-unit").length > 0) {
                var $lottery = $("#" + id);
                var $units = $lottery.find(".lottery-unit");
                this.obj = $lottery;
                this.count = $units.length;
                $lottery.find(".lottery-unit-" + this.index).addClass("active");
            };
        },
        roll: function () {
            var index = this.index;
            var count = this.count;
            var lottery = this.obj;
            $(lottery).find(".lottery-unit-" + index).removeClass("active");

            index += 1;
            if (index > count) {
                index = 1;
            };
            $(lottery).find(".lottery-unit-" + index).addClass("active");
            this.index = index;
            return false;
        },
        stop: function (index) {
            this.prize = index;
            return false;
        },
        changeLight: function () {
            this.timer = setInterval(function () {
                if (this.isLight) {
                    this.isLight = false;
                    $('#marquee').attr('src', 'https://h5.wdb007.com/lottery-image/marquee-1.png');
                } else {
                    this.isLight = true;
                    $('#marquee').attr('src', 'https://h5.wdb007.com/lottery-image/marquee-2.png');
                }
            }.bind(this), 300)
        },
    };

    function roll() {
        lottery.times += 1;
        lottery.roll(); //转动过程调用的是lottery的roll方法，第一次调用初始化
        var prize_index = $("#lottery").attr("prize_index");
        if (lottery.times > lottery.cycle + 10 && prize_index == lottery.index) {
            clearTimeout(lottery.timer);
            setTimeout(function () {
                getPrizeList();
                pageNo = 1;
                rankList = [];
                getPrizeRankList(pageNo);
                $('.shadow_box').hide();
                $('#prize_shadow').show();
            }, 1500)

            lottery.prize = 1;
            lottery.times = 0;
        } else {
            if (lottery.times < lottery.cycle) {
                lottery.speed -= 10;
            } else if (lottery.times == lottery.cycle) {
                var index = Math.random() * (lottery.count) | 0;
                lottery.prize = index;
            } else {
                if (lottery.times > lottery.cycle + 10 && ((lottery.prize == 0 && lottery.index == 7) || lottery.prize == lottery.index + 1)) {
                    lottery.speed += 110;
                } else {
                    lottery.speed += 20;
                }
            }
            if (lottery.speed < 40) {
                lottery.speed = 40;
            };
            lottery.timer = setTimeout(roll, lottery.speed); //循环调用
        }
        return false;
    }

    // 获取抽奖信息
    function getPrizeList() {
        var usertoken = sessionStorage.getItem('usertoken');
        var userid = sessionStorage.getItem('userid');
        // alert(userid)
        var postData = {
            userid: userid,
            usertoken: usertoken,
            parentHdUid: parentHdUid,
            activityId: 'lotteryInfo001'
        }
        var postDataNor = {
            usertoken: usertoken,
            parentHdUid: parentHdUid,
            activityId: 'lotteryInfo001'
        }
        console.log('getPrizeList', usertoken == 'undefined')
        var data = userid != 'undefined' ? postData : postDataNor;
        var url = hostUrl + 'lottery/getLotteryInfo';

        console.log('getPrizeList---Data', data);
        var header = getHeader(url, data);
        if(usertoken || usertoken!='undefined'){
            $.ajax({
                type: 'POST',
                data: data,
                url: url,
                headers: header,
                success: function (res) {
                    console.log('getPrizeList---success', res);
                    if (res.code == 1020070002) {
                        $('#overtime_container').show();
                        return
                    }
                    if (res.result == 1 && res.code == 0) {
                        var prizeList = res.items;
                        var startHtml = '<div id="start_roll"><img src="../img/star_roll.png" alt=""></div>';
                        var topPrizeList = '';
                        var bottomPrizeList = '';
                        var sevenIndexList = '<div class="lottery-unit lottery-unit-' + prizeList[7].location + '"><div class="td_container"><img src="' + prizeList[7].lotteryImg + '"><div class="lottery-unit-text">' + prizeList[7].lotteryName + '</div></div><div class="mask"></div></div>';
                        var threeIndexList = '<div class="lottery-unit lottery-unit-' + prizeList[3].location + '"><div class="td_container"><img src="' + prizeList[3].lotteryImg + '"><div class="lottery-unit-text">' + prizeList[3].lotteryName + '</div></div><div class="mask"></div></div>';
                        for (var i = 0; i < 3; i++) {
                            topPrizeList += '<div class="lottery-unit lottery-unit-' + prizeList[i].location + '"><div class="td_container"><img src="' + prizeList[i].lotteryImg + '"><div class="lottery-unit-text">' + prizeList[i].lotteryName + '</div></div><div class="mask"></div></div>';
                        }
                        for (var j = 6; j > 3; j--) {
                            bottomPrizeList += '<div class="lottery-unit lottery-unit-' + prizeList[j].location + '"><div class="td_container"><img src="' + prizeList[j].lotteryImg + '"><div class="lottery-unit-text">' + prizeList[j].lotteryName + '</div></div><div class="mask"></div></div>';
                        }
                        $('.unit_container').html(topPrizeList + sevenIndexList + startHtml + threeIndexList + bottomPrizeList);
                        if (res.detail.lotteryCount != 0) {
                            $("#lottery").attr("prize_index", res.detail.lotteryInfo.location);
                            $('#lottery').attr('loterryAwardId', res.detail.lotteryInfo.loterryAwardId);
                            $('#lottery').attr('lotteryContent', res.detail.lotteryInfo.lotteryContent);
                            $('#lottery').attr('lotteryName', res.detail.lotteryInfo.lotteryName);
                            $('#lotteryLocation').html(res.detail.lotteryInfo.location);
                        }
                        $('#lottery').attr('lotteryCount', res.detail.lotteryCount);
                        $('#extra_times').html(res.detail.lotteryCount);
                    } else {
                        console.log(res.message);
                    }
                },
                fail: function (err) {
                    console.log('getPrizeList---err', err);
                }
            })
        }
    }


    function getPrizeRankList(pageNo) {
        var usertoken = sessionStorage.getItem('usertoken');
        var userid = sessionStorage.getItem('userid');
        // alert(userid);
        var postData = {
            userid: userid,
            usertoken: usertoken,
            pagesize: 5,
            pageno: pageNo,
            activityId: 'lotteryInfo001'
        }
        var postDataNor = {
            usertoken: usertoken,
            pagesize: 5,
            pageno: pageNo,
            activityId: 'lotteryInfo001'
        }
        var data = userid != 'undefined' ? postData : postDataNor;
        console.log('getPrizeRankList---Data', data);
        var url = hostUrl + 'lottery/listFriendsLottery'
        var header = getHeader(url, data);
        if(usertoken || usertoken!='undefined'){
            $.ajax({
                type: 'POST',
                data: data,
                url: url,
                headers: header,
                success: function (res) {
                    console.log('getPrizeRankList-----res', res);
                    var list = res.items;
                    // $('#lotteryinfo').html(JSON.stringify(list));
                    if (list.length != 0) {
                        for (var i = 0; i < list.length; i++) {
                            rankList.push(list[i])
                        }
                        showRankList(rankList);
                    }
    
                    if (list.length == 5) {
                        $('.load_more').show();
                        $('.no_hasdata').hide();
    
                    } else {
                        $('.load_more').hide();
                        $('.no_hasdata').show();
                    }
    
                    // }else{
                    //     $('.load_more').hide();
                    //     $('.no_hasdata').show();
                    // }
    
                },
                fail: function (err) {
                    console.log('getPrizeRankList--------err', err);
                }
            })
        }
        
    }

    // 好友玲无奖品信息展示
    function showRankList(list) {
        if (list.length == 0) {
            $('#hasNo_data').show();
            $('.rank_container').hide();
            return
        }
        var rankHtml = '';
        for (var i = 0; i < list.length; i++) {
            var item = list[i];
            rankHtml += "<div class='rank_item'><div class='user_info'><img class='user_img' src='" + item.headImg + "' alt=''><div class='user_name'><div class='nick_name'>" + item.nickName + "</div><div class='get_date'>" + item.createTime + "</div></div></div><div class='prize_detail'>" + item.loterryName + "</div></div>";
        }
        $(".rank_item_container").html(rankHtml);
    }

    lottery.init('lottery');
    lottery.changeLight();
    getPrizeList();
    var pageNo = 1;
    rankList = [];
    getPrizeRankList(pageNo);

    // 点击抽奖
    $(document).on('click', '#start_roll', function () {
        var lotteryCount = $('#lottery').attr('lotteryCount');
        if (!lotteryCount) {
            return
        }
        if (lotteryCount == 0) {
            $('#noCount_container').show();
            return
        }
        var loterryAwardId = $('#lottery').attr('loterryAwardId');
        var data = {
            loterryAwardId: loterryAwardId
        };
        var url = hostUrl + 'lottery/receivePersonalLottery'
        var header = getHeader(url, data);
        $.ajax({
            type: 'POST',
            data: data,
            url: url,
            headers: header,
            success: function (res) {
                console.log('receivePersonalLottery-----res', res);
                lottery.speed = 100;
                $('.shadow_box').show();
                roll();
                if (res.detail.lotteryType == 2) {
                    $('#continueLottery').show();
                    $('#getPrizeBtn').hide();
                } else {
                    $('#continueLottery').hide();
                    $('#getPrizeBtn').show();
                }
                $('.prize_detail_text').html(res.detail.lotteryName);
                $('.get_prize_info').html(res.detail.lotteryContent);
                sessionStorage.setItem('lotterySuccessContent', res.detail.lotterySuccessContent);
                sessionStorage.setItem('loginStatus', res.detail.loginStatus);
                if (res.detail.couponBookShelfInfo.length != 0) {
                    var html = "";
                    for (var i = 0; i < res.detail.couponBookShelfInfo.length; i++) {
                        var item = res.detail.couponBookShelfInfo[i];
                        html += "<div class='shelf_list_item'><div class='shelf_code'>" + (i + 1) + "." + item.area + "</div><div class='shelf_address'>地址：" + item.address + "</div><div class='business_time'>营业时间：" + item.policyRule + "</div></div>";
                    }
                    $('#shelf_list_container').html(html);
                    $('#shelf_list').show();
                    $('.prize_scroll_container').css('height',250);
                } else {
                    $('#shelf_list').hide();
                    $('.prize_scroll_container').css('height',200);
                }
            },
            fail: function (err) {
                console.log('receivePersonalLottery--------err', err);
            }
        })

    })

    $('.load_more').click(function () {
        pageNo += 1;
        getPrizeRankList(pageNo);
    })

    // 关闭获奖信息弹窗
    $('.shut_prize_shadow').click(function () {
        // rankList = [];
        // pageNo = 1;
        // getPrizeRankList(pageNo);
        // getPrizeList();
        $('#prize_shadow').hide();
        $('#shelf_list').hide();
        $('.prize_scroll_container').css('height',200);
    })

    $('#continueLottery').click(function () {
        // rankList = [];
        // pageNo = 1;
        // getPrizeRankList(pageNo);
        // getPrizeList();
        $('#prize_shadow').hide();
        $('#shelf_list').hide();
        $('.prize_scroll_container').css('height',200);
    })

    $('#prize_shadow').click(function () {
        // rankList = [];
        // pageNo = 1;
        // getPrizeRankList(pageNo);
        // getPrizeList();
        $(this).hide();
        $('#shelf_list').hide();
        $('.prize_scroll_container').css('height',200);
    })

    // 点击领取跳转页面
    $('#getPrizeBtn').click(function () {
        getPrizeList();
        if (sessionStorage.getItem('loginStatus') == 1) {
            wx.miniProgram.navigateTo({
                url: '../../success/lottery_success/lottery_success?gift_content=' + sessionStorage.getItem('lotterySuccessContent')
            })
        } else {
            $('#lottery_page').hide();
            $('#lottery_login').show();
        }
    })

    // 返回小程序首页
    $('#goto_index').click(function () {
        wx.miniProgram.reLaunch({
            url: '../../index/index'
        })
    })

    // 展示活动规则
    $('#rule_btn').click(function () {
        $('#shadow_container').show()
    })

    // 关闭活动规则
    $('.shut_rule_shadow').click(function () {
        $('#shadow_container').hide();
    })

    // 关闭获奖次数为0的弹窗
    $('#confirBtn_container_noCount').click(function () {
        $('#noCount_container').hide();
    })

    // 关闭活动过期弹窗
    $('#confirBtn_container_overtime').click(function () {
        $('#overtime_container').hide();
    })

    // 打开分享页面引导图片
    $('#share_btn').click(function () {
        $('#lead_picture').show();
    })

    // 关闭引导页
    $('#lead_picture').click(function () {
        $(this).hide()
    })

    window.onload = function () {


    };


















})